package com.vote.admin.job;

import cn.hutool.core.collection.CollectionUtil;
import com.vote.common.entity.VoteProject;
import com.vote.common.enums.VoteStatusEnum;
import com.vote.common.service.VoteProjectService;
import com.vote.common.utils.TimeUtilCustomize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class VoteTimeJob {

    @Autowired
    private VoteProjectService voteProjectService;

    /**
     * 更新活动状态定时任务 每10秒执行一次
     */
    @Scheduled(cron="0/10 * * * * ?")
    public void voteTime() {
        long time = new Date().getTime();
        List<VoteProject> voteProjectList = voteProjectService.list();
        if (CollectionUtil.isNotEmpty(voteProjectList)) {
            for (VoteProject voteProject : voteProjectList) {
                Date start = TimeUtilCustomize.parseStrToDate(TimeUtilCustomize.DATE_TIME_FORMAT, voteProject.getProjectStart());
                Date end = TimeUtilCustomize.parseStrToDate(TimeUtilCustomize.DATE_TIME_FORMAT, voteProject.getProjectEnd());

                //投票未开始
                if (time < start.getTime()) {
                    if (voteProject.getProjectStatus().equals(VoteStatusEnum.NOT_STARTED.getCode())) {
                        continue;
                    }
                    log.info("投票活动：{}, 未开始", voteProject.getId());
                    voteProject.setProjectStatus(VoteStatusEnum.NOT_STARTED.getCode());
                    voteProjectService.updateById(voteProject);
                    continue;
                }

                //投票进行中
                if (time >= start.getTime() && time < end.getTime()) {
                    if (voteProject.getProjectStatus().equals(VoteStatusEnum.IN_PROGRESS.getCode())) {
                        continue;
                    }
                    log.info("投票活动：{}, 开始投票", voteProject.getId());
                    voteProject.setProjectStatus(VoteStatusEnum.IN_PROGRESS.getCode());
                    voteProjectService.updateById(voteProject);
                    continue;
                }

                //投票已结束
                if (time > end.getTime()) {
                    if (voteProject.getProjectStatus().equals(VoteStatusEnum.FINISH.getCode())) {
                        continue;
                    }
                    log.info("投票活动：{}, 已经结束投票", voteProject.getId());
                    voteProject.setProjectStatus(VoteStatusEnum.FINISH.getCode());
                    voteProjectService.updateById(voteProject);
                    continue;
                }
            }
        }

    }

}
